package com.mengshu.platform.utils;

import lombok.SneakyThrows;

import java.security.MessageDigest;
import java.util.UUID;

public class PasswordUtils {

    /**
     * @return 生成密码需要的盐
     */
    public static String generateSalt(){
        return UUID.randomUUID().toString();
    }

    /**
     * 生成密文密码
     *
     * @param password
     * @param salt
     * @return sha256
     */
    @SneakyThrows
    public static String SHA256(String password, String salt){
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update((password + salt).getBytes("UTF-8"));
        return byte2Hex(messageDigest.digest());
    }

    /**
     * 将byte转为16进制
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp;
        for (int i = 0; i < bytes.length; i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

}
